package com.hyjx.framework.component.interfaceservice;

import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.hyjx.framework.orm.dao.Pager;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.hyjx.framework.component.interfaceservice.dataservice.DataServiceModel;
import com.hyjx.framework.component.interfaceservice.dataservice.SrvConditionModel;
import com.hyjx.framework.orm.dao.IBaseDao;
import org.springframework.transaction.annotation.Transactional;

/**
 * 接口服务接口实现类
 */
@Service
@Transactional
public class InterfaceServiceImpl implements InterfaceService{

	@Resource
	private IBaseDao dao;
	
	public IBaseDao getDao() {
		return dao;
	}


	public void setDao(IBaseDao dao) {
		this.dao = dao;
	}

	public static final String MODULE_NAME = InterFaceConstants.INTERFACE_MODULE_NAME;

	public InterfaceServiceImpl(){
		//System.out.println("I am InterfaceServiceImpl");
	}

	@Override
	public DataServiceModel findDataService(String srvid){
		return (DataServiceModel) dao.queryObject(MODULE_NAME + ".searchService",srvid);
	}
	
	@Override
	public UserInfoModel findUserInfo(String userid){
		return (UserInfoModel) dao.queryObject(MODULE_NAME + ".searchUserInfo",userid);
	}
	@Override
	public String findSqlDesc(String srvId){
		DataServiceModel dsm=new DataServiceModel();
		dsm.setSrvid(srvId);
		SrvConditionModel scm=new SrvConditionModel();
		scm.setSrvid(srvId);
		List dsmlist=dao.queryObjectList(MODULE_NAME + ".serchServiceDesc", srvId);
		List scmlist=dao.queryObjectList(MODULE_NAME + ".serchServiceDescCondition", srvId);

		
		List<Map<String,String>> scmlisttemp=new ArrayList<Map<String,String>>();
		
			DataServiceModel servicetemp=(DataServiceModel) dsmlist.get(0);
			Map<String,String>servicetempmap=new HashMap<String,String>();
			servicetempmap.put("servicename", servicetemp.getSrvname());
			servicetempmap.put("interfacedesc",servicetemp.getInterfacedesc());
			
		
		
		for(int i=0;i<scmlist.size();i++){
			SrvConditionModel temp=(SrvConditionModel) scmlist.get(i);
			Map<String,String>tempmap=new HashMap<String,String>();
			tempmap.put("parametername", temp.getParameter());
			if(temp.getType().equals("1")){
				tempmap.put("paratype","字符串");
			}else{
				tempmap.put("paratype","整型");
			}
			
			if(temp.getRequired().equals("1")){
				tempmap.put("required", "是");
			}else{
				tempmap.put("required", "否");
			}
			
			
			tempmap.put("parameter_means", temp.getParameter_means());
			scmlisttemp.add(tempmap);
		}
		
		Map<String,Object>map1=new HashMap<String,Object>();
		
		map1.put("servicecondition", scmlisttemp);
		map1.put("service", servicetempmap);
		JSONObject json = JSONObject.fromObject(map1); 
		return json.toString();
		//return (String) dao.queryObject(MODULE_NAME + ".serchServiceDesc",srvId);
		
	}
	@Override
	public List queryMap(String sql) {
		return dao.queryObjectList(MODULE_NAME + ".Servicetemp", sql);
	}
	
	//导入数据
	@Override
	public boolean  insertData(String sql){
		boolean con=dao.addObject(MODULE_NAME + ".insertdata", sql);
		return con;
	}
	//更新数据
	@Override
	public int  updateData(String sql){
		int con=dao.updateObject(MODULE_NAME + ".updatedata", sql);
		return con;
	}
	
	
	
	//分页查找
	@Override
	public List queryPager(String sql,String pageNo,String pageSize){
		int int_no = Integer.parseInt(pageNo);
		int int_size = Integer.parseInt(pageSize);
		
		int ibegin = (int_no - 1) * int_size;
		
		Pager pager = dao.getPager(MODULE_NAME + ".Servicetemp", MODULE_NAME + ".ServicetempCount", sql, ibegin, int_size);
		
		return pager.getResultList();
	}
	
	//分页查找
	@Override
	public Pager queryPagerAll(String sql,String pageNo,String pageSize){
		int int_no = Integer.parseInt(pageNo);
		int int_size = Integer.parseInt(pageSize);
		
		int ibegin = (int_no - 1) * int_size;
		
		return dao.getPager(MODULE_NAME + ".Servicetemp", MODULE_NAME + ".ServicetempCount", sql, ibegin, int_size);
		
	}
	
	//分页查找1
	@Override
	public Map queryPagerP(int dbType, String sql,String pageNo,String pageSize){
		List list = null;
		List listNum=null;
		List finlist=new ArrayList<Object>();
		
		if(pageSize.equals("-1")||pageNo.equals("-1")){
			String querySql = getQuerySql(dbType, sql, 1, 10);
			listNum=dao.queryObjectList(MODULE_NAME + ".Servicetemp", querySql);
			Map countMap = (Map)dao.queryObject(MODULE_NAME + ".ServicetempCount", sql);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("list", listNum);
			map.put("total", ""+(countMap.get("num")==null?countMap.get("NUM"):countMap.get("num")));
			return map;

		}else{
			int int_no = Integer.parseInt(pageNo);
			int int_size = Integer.parseInt(pageSize);
			
			int ibegin = (int_no - 1) * int_size;
			//sql="select * from srv_userinfo";
			//SqlMapClientDaoSupport sqlmap=new SqlMapClientDaoSupport();
			//list =dao.getSqlMapClientTemplate1().queryForList(MODULE_NAME + ".Servicetemp", sql, ibegin, int_size);
			String querySql = getQuerySql(dbType, sql, ibegin, ibegin+int_size);
			finlist = dao.queryObjectList(MODULE_NAME + ".Servicetemp", querySql);
			Map countMap = (Map)dao.queryObject(MODULE_NAME + ".ServicetempCount", sql);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("list", finlist);
			map.put("total", ""+(countMap.get("num")==null?countMap.get("NUM"):countMap.get("num")));
			return map;
		}
		
		
	}
	
	/**
	 * 通过数据连接获得查询分页数据
	 * @param con
	 * @param sql
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * @throws Exception 
	 */
	@Override
	public Map queryPagerByConnection(int dbType, Connection con, String sql,String pageNo,String pageSize) throws Exception{
		List<Map> listRow = new ArrayList<Map>();
		if(pageSize.equals("-1")){
			pageSize = "10";
		}
		if(pageNo.equals("-1")){
			pageNo = "1";
		}
		int int_no = 1;
		int int_size = 10;
		try{
			int_no = Integer.parseInt(pageNo);
		}catch(Exception e){
			e.printStackTrace();
		}
		try{
			int_size = Integer.parseInt(pageSize);
		}catch(Exception e){
			e.printStackTrace();
		}
		int startNum = (int_no - 1) * int_size;
		int endNum = startNum+int_size;
		String querySql = getQuerySql(dbType, sql, startNum, endNum);
		String countSql = "select count(1) as num from ("+sql+") temptable";
		java.sql.Statement st = con.createStatement();
		java.sql.ResultSet rs = st.executeQuery(querySql);
		ResultSetMetaData rsmd = rs.getMetaData();
		int numCols = rsmd.getColumnCount();
		List<DbColumn> columnList = new ArrayList<DbColumn>();
		for(int i = 0; i < numCols; i++){
			DbColumn dc = new DbColumn();
			dc.setName(rsmd.getColumnName(i+1));
			dc.setType(rsmd.getColumnTypeName(i+1).toUpperCase());
			columnList.add(dc);
		}
		String cols_value = null;
		while(rs.next()){
			Map<String, String> rowMap = new HashMap<String, String>();
			for(DbColumn dc:columnList){
				if(dc.getType().equals("CLOB")){
					Clob clob = rs.getClob(dc.getName());
					if(clob != null){
						Reader reader = clob.getCharacterStream();
						int charsize = (int)clob.length();
						char[] chars = new char[charsize];
						reader.read(chars);
						reader.close();
						cols_value = new String(chars);
					}else{
						cols_value = "";
					}
				}else{
					cols_value = rs.getString(dc.getName());
				}
				rowMap.put(dc.getName(), cols_value);
			}
			listRow.add(rowMap);
		}
		rs.close();
		int totalNum = 0;
		rs = st.executeQuery(countSql);
		if(rs.next()){
			totalNum = rs.getInt(1);
		}
		rs.close();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("list", listRow);
		map.put("total", ""+totalNum);
		return map;

			
			
	
		
	}
	
	/**
	 * 根据数据库类型，查询开始和结束记录数，获得要执行的sql
	 * @param dbType
	 * @param sql
	 * @param startNum
	 * @param endNum
	 * @return
	 */
	private String getQuerySql(int dbType, String sql, int startNum, int endNum){
		StringBuffer sb;
		//数据库为oracle
		if(dbType == 1){
			sb = new StringBuffer();
			sb.append("SELECT * FROM (");
			sb.append("SELECT ROWNUM AS ROWNUM_, TMP_.* from (");
			sb.append(sql);
			sb.append(") TMP_ where rownum<=" + endNum);
			sb.append(") WHERE ROWNUM_ > " + startNum);
		}
		//数据库为mysql
		else if(dbType == 2){
			sb = new StringBuffer(sql.length() + 20);
			  sb.append(sql);
			  if (startNum > 0) {
				  sb.append(" limit ").append(startNum).append(',').append(endNum - startNum)
						  .append(";");
			  } else {
				  sb.append(" limit ").append(endNum).append(";");
			  }
		}else{
			sb = new StringBuffer(sql);
		}
		return sb.toString();
	}
	
	
	
	//在srv_user_service表里面判断是否用户有相应的服务权限
	@Override
	public String limitAdmit(ConditionModel model){
		return (String) dao.queryObject(MODULE_NAME + ".limitAdmit",model);
	}
	
	//查看是否存在userid信息
	@Override
	public List queryUserInfo(){
		return dao.queryObjectList(MODULE_NAME + ".searchUserModelInfo",null);
	}
	
	//查看服务信息
	@Override
	public List queryDataService(){
		return dao.queryObjectList(MODULE_NAME + ".searchDataService",null);
	}

	//查看服务所需条件信息
	@Override
	public List queryDataConditionService(String str){
		return dao.queryObjectList(MODULE_NAME + ".searchDataConditionService",str);
	}
	
	
	//服务请求日志记录
	@Override
	public boolean  srvRequestLog(InterfaceLogModel model){
		boolean con=dao.addObject(MODULE_NAME + ".addrequestlog", model);
		return con;
	}
	
	
	
	
	//根据用户登录名查找用户id
	@Override
		public String queryUserIdByLogName(String model) {
			String userid = (String) dao.queryObject("interface_useradmitservice.finduseridbylogname",model);
			return userid;
		}
}

class DbColumn{
	private String name;
	private String type;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
}
